/**
 * Created by Ivan Babanin (22.07.2007 1:42:36)
 * This part of code is strictly confidential.
 * © Magnificent Software Inc.
 */
package com.silverhaze.diamond.client.ui.filter;

import com.silverhaze.commons.db.datasource.ObjectEntity;
import com.silverhaze.commons.helpers.CommonUIHelper;
import com.silverhaze.commons.ui.simpledatepicker.SimpleDatePicker;
import com.silverhaze.commons.ui.simpledatepicker.SimpleDatePickerListener;
import com.silverhaze.commons.utils.DateUtils;
import com.silverhaze.diamond.client.data.SpecificData;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.client.resources.ServiceResourceContainer;
import com.silverhaze.diamond.client.settings.SettingsStorage;
import com.silverhaze.diamond.client.settings.ui.service.ServicePanelSettings;
import com.silverhaze.diamond.client.ui.table.model.ServiceTableModel;
import com.silverhaze.diamond.common.entity.SystemUser;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import java.util.Date;

public class ServiceFilterPanel extends AbstractFilterPanel {
    // Field filter
    private JTextField ownerField;
    private JTextField deviceField;
    private JTextField serialNumberField;
    private JComboBox userBox;

    // Time filter
    private SimpleDatePicker fromDatePicker;
    private SimpleDatePicker tillDatePicker;

    // View filter
    private JCheckBox showInService;
    private JCheckBox showCompleted;


    public ServiceFilterPanel(ServiceTableModel model, JToggleButton tBtn) {
        super(model, tBtn);

        init();
    }

    private void init() {
        setLayout(new BorderLayout());

        Box hBoxFirstLine = CommonUIHelper.createHorizontalBox(
                initViewFilter(),
                initTimeFilter()
        );

        Box hBoxSecondLine = CommonUIHelper.createHorizontalBox(
                initFieldFilter()
        );

        Box vBox = CommonUIHelper.createVerticalBox(
                hBoxFirstLine,
                hBoxSecondLine
        );

        fillWithSettings();

        add(vBox, BorderLayout.CENTER);
    }

    public void applyData() {
        saveToSettings();

        String owner = ownerField.getText().trim();
        String device = deviceField.getText().trim();
        String serialNumber = serialNumberField.getText().trim();

        Date fromDate = fromDatePicker.getDate();
        Date tillDate = tillDatePicker.getDate();

        boolean isShowComplete = showCompleted.isSelected();
        boolean isShowInService = showInService.isSelected();

        SystemUser user = null;
        Object o = userBox.getSelectedItem();
        if (o instanceof SystemUser) {
            user = (SystemUser) o;
        }

        getModel().fillData(SpecificData.filterServices(owner, device, serialNumber, user, fromDate, tillDate, isShowComplete, isShowInService, DAOLocator.getInstance().getServices()));
    }

    private void saveToSettings() {
        ServicePanelSettings settings = SettingsStorage.getSettings().getUiSettings().
                getServiceTabSettings().getServicePanelSettings();

        settings.setFrom(fromDatePicker.getDate());
        settings.setTill(tillDatePicker.getDate());

        settings.setCompletedEnabled(showCompleted.isSelected());
        settings.setInServiceEnabled(showInService.isSelected());
    }

    private void fillWithSettings() {
        ServicePanelSettings settings = SettingsStorage.getSettings().getUiSettings().
                getServiceTabSettings().getServicePanelSettings();

        Date currentDate = new Date();
        Date from = settings.getFrom();
        if (from == null) {
            from = new Date(DateUtils.roll(currentDate.getTime(), Calendar.YEAR, 1));
        }

        Date till = settings.getTill();
        if (till == null) {
            till = new Date(DateUtils.add(currentDate.getTime(), Calendar.DAY_OF_MONTH, 1));
        }

        fromDatePicker.setDate(from);
        tillDatePicker.setDate(till);

        showInService.setSelected(settings.isInServiceEnabled());
        showCompleted.setSelected(settings.isCompletedEnabled());

        showCompleted.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                applyData();
            }
        });

        showInService.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                applyData();
            }
        });

        applyData();
    }

    private JPanel initFieldFilter() {
        JPanel panel = new JPanel(new BorderLayout());

        ownerField = createTextField(10);
        deviceField = createTextField(10);
        serialNumberField = createTextField(10);
        userBox = new JComboBox(getUserBoxModel());
        userBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                applyData();
            }
        });

        JButton clearBtn = new JButton(ServiceResourceContainer.UNDO);
        clearBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ownerField.setText("*");
                deviceField.setText("*");
                serialNumberField.setText("*");

                getModel().refreshModelAll();
            }
        });

        Box hBox = CommonUIHelper.createHorizontalBox(
                "Владелец: ", 3, ownerField, 6,
                "Устройство: ", 3, deviceField, 6,
                "Серийный номер: ", 3, serialNumberField, 6,
                "Пользователь: ", 3, userBox
        );

        Box vBox = CommonUIHelper.createVerticalBox(
                hBox, 5
        );

        panel.add(vBox, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createTitledBorder(" Содержание "));

        return panel;
    }

    private Object[] getUserBoxModel() {
        java.util.List<ObjectEntity> users = DAOLocator.getInstance().getUsers();
        Object[] result = new Object[users.size() + 1];

        result[0] = "любой";
        for (int i = 0; i < users.size(); i++) {
            result[i + 1] = users.get(i);
        }

        return result;
    }

    private JPanel initViewFilter() {
        JPanel panel = new JPanel(new BorderLayout());

        showInService = new JCheckBox("в сервисе");
        showCompleted = new JCheckBox("завершенные");

        Box hViewBox = CommonUIHelper.createHorizontalBox(
                6, "Показывать: ", 3,
                showInService, 3,
                showCompleted
        );

        panel.add(hViewBox, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createTitledBorder(" Просмотр "));

        return panel;
    }

    private JPanel initTimeFilter() {
        JPanel panel = new JPanel(new BorderLayout());

        fromDatePicker = new SimpleDatePicker();
        fromDatePicker.addListener(new SimpleDatePickerListener() {
            public void dateChanged(Date newDate) {
                applyData();
            }
        });

        tillDatePicker = new SimpleDatePicker();
        tillDatePicker.addListener(new SimpleDatePickerListener() {
            public void dateChanged(Date newDate) {
                applyData();
            }
        });

        Box hBox = CommonUIHelper.createHorizontalBox(
                "от ", 3,
                fromDatePicker, 5,
                " до ", 5,
                tillDatePicker, 5
        );

        panel.add(hBox, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createTitledBorder(" Период "));

        return panel;
    }

    private JTextField createTextField(int size) {
        JTextField field = new JTextField(size);
        field.setText("*");
        field.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent event) {
                applyData();
            }
        });

        return field;
    }
}

